package org.example.auth.config.oauth.granter;

import com.alibaba.fastjson.JSON;
import org.example.auth.domain.MobileLoginBody;
import org.example.auth.domain.PasswordLoginBody;
import org.example.common.core.constants.CacheConstants;
import org.example.common.core.constants.Constants;
import org.example.common.core.enums.GrantUser;
import org.example.common.core.exception.base.BaseException;
import org.example.common.core.utils.MapstructUtils;
import org.example.common.core.utils.StringUtils;
import org.example.common.redis.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.util.ObjectUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自定义手机号登录
 */
public class MobileTokenGranter extends AbstractTokenGranter {

    private static final String GRANT_TYPE = "mobile";
    private static final String GRANT_USER = Constants.GRANT_USER;
    private static final String DEVICE_TYPE = Constants.DEVICE_TYPE;


    private final AuthenticationManager authenticationManager;

    public MobileTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
    }

    protected MobileTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
                                 ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String,String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        MobileLoginBody mobileLoginBody= JSON.parseObject(JSON.toJSONString(parameters), MobileLoginBody.class);
        if(ObjectUtils.isEmpty(client.getAdditionalInformation()))  throw new BaseException("客户端参数错误");
        String user_type =(String)client.getAdditionalInformation().get(GRANT_USER);
        String device_type =(String)client.getAdditionalInformation().get(DEVICE_TYPE);
        GrantUser grantUser= GrantUser.valueOf(user_type.toUpperCase());
        mobileLoginBody.setGrant_user(grantUser);
        mobileLoginBody.setExpires_in(client.getAccessTokenValiditySeconds());
        mobileLoginBody.setGrant_type(GRANT_TYPE);
        mobileLoginBody.setDevice_type(device_type);
        mobileLoginBody.setClient_Id(client.getClientId());
        Authentication userAuth = new UsernamePasswordAuthenticationToken(mobileLoginBody.getMobile(),null);
        ((AbstractAuthenticationToken) userAuth).setDetails(mobileLoginBody);
        try {
            userAuth = authenticationManager.authenticate(userAuth);
        }
        catch (AccountStatusException ase) {
            throw new InvalidGrantException(ase.getMessage());
        }
        catch (BadCredentialsException e) {
            throw new InvalidGrantException(e.getMessage());
        }
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate user: "+client.getClientId());
        }
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }
}
